package com.red.wood.common.util;

import java.io.IOException;

import net.sf.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp3Client {

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    
    public static String httpGet(String url) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string(); // 返回的是string 类型，json的mapper可以直接处理
    }
 
    public static String httpPost(String url, String json) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }
    
    public static void main(String[] args) throws IOException {
    	String url = "http://localhost:8090/accumulative/restFul/requestDataForGet?id=1";
    	System.out.println(OkHttp3Client.httpGet(url));
    	url = "http://localhost:8090/accumulative/restFul/requestDataForPost";
    	String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据.
    	JSONObject jsonParams = new JSONObject();
    	jsonParams.put("name","xl");
    	//post 接收服务，需要用@RequestBody注解来接收参数
    	System.out.println(OkHttp3Client.httpPost(url,jsonStr));
    	System.out.println(OkHttp3Client.httpPost(url,jsonParams.toString()));
	}
}
